package com.tanhua.dubbo.api.impl.mongo;

import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.mongo.PublishApi;
import com.tanhua.dubbo.utils.IdService;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@Service
public class PublishApiImpl implements PublishApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdService IdService;

    @Override
    public void save(Publish publish) {
        //1. 插入朋友圈
        publish.setCreated(System.currentTimeMillis());
        publish.setPid(IdService.getNextId("quanzi_publish"));
        mongoTemplate.insert(publish);

        //2. 插入相册表
        Album album = new Album();
        album.setPublishId(publish.getId());
        album.setCreated(System.currentTimeMillis());
        mongoTemplate.insert(album,"quanzi_album_"+publish.getUserId());


        //3. 查询好友
        Query query = new Query(Criteria.where("userId").is(publish.getUserId()));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        //4. 往好友的时间线表插入
        if(friendList!=null){
            for (Friend friend : friendList) {
                TimeLine timeLine = new TimeLine();
                timeLine.setUserId(publish.getUserId());
                timeLine.setPublishId(publish.getId());
                timeLine.setCreated(System.currentTimeMillis());
                mongoTemplate.insert(timeLine,"quanzi_time_line_"+friend.getFriendId());
            }
        }
    }

    //查询好友朋友圈
    @Override
    public PageResult findByTimeLine(Integer page, Integer pageSize, long userId) {
        //1. 查询时间线表，得到我的好友的朋友圈id
        Query query = new Query();
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page-1)*pageSize).limit(pageSize);

        List<TimeLine> timeLineList= mongoTemplate.find(query, TimeLine.class, "quanzi_time_line_" + userId);
        long count = mongoTemplate.count(query, TimeLine.class, "quanzi_time_line_" + userId);

        //遍历时间线表，得到所有的publishId
        List<Publish> publishList = new ArrayList<>();
        if(timeLineList!=null){
            for (TimeLine timeLine : timeLineList) {
                Publish publish = mongoTemplate.findById(timeLine.getPublishId(), Publish.class);

                //注意：由于我们的测试数据存在着脏数据，所以一定要判断
                if(publish!=null) {
                    publishList.add(publish);
                }
            }
        }


        PageResult pageResult = new PageResult(page,pageSize,(int)count,publishList);
        return pageResult;
    }


    //查询圈子表，得到PageResult
    @Override
    public PageResult queryRecommendPublishList(Integer page, Integer pageSize, long userId) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("created"))).skip((page-1)*pageSize).limit(pageSize);

        List<RecommendQuanzi> recommendQuanziList= mongoTemplate.find(query, RecommendQuanzi.class);
        long count = mongoTemplate.count(query, RecommendQuanzi.class);


        //遍历所有的推荐圈子，得到圈子的id，然后查询Publish
        List<Publish> publishList = new ArrayList<>();
        if(recommendQuanziList!=null){
            for (RecommendQuanzi recommendQuanzi : recommendQuanziList) {
                Publish publish = mongoTemplate.findById(recommendQuanzi.getPublishId(), Publish.class);

                //注意：由于我们的测试数据存在着脏数据，所以一定要判断
                if(publish!=null) {
                    publishList.add(publish);
                }
            }
        }


        PageResult pageResult = new PageResult(page,pageSize,(int)count,publishList);
        return pageResult;
    }

    //根据id查找publish
    @Override
    public Publish findById(String publishId) {
        Publish publish = mongoTemplate.findById(new ObjectId(publishId), Publish.class);
        return publish;
    }

    @Override
    public PageResult queryMyPublishList(Integer page, Integer pagesize, Long userId) {
        // 创建查询对象
        Query query = new Query();
        // 指定排序参数
        query.with(Sort.by(Sort.Direction.DESC, "created"));
        // 指定分页参数
        query.limit(pagesize).skip((page - 1) * pagesize);

        // 查询当前用户的相册表
        List<Album> albumList = mongoTemplate.find(query, Album.class,"quanzi_album_" + userId);

        // 获取总条数
        long count = mongoTemplate.count(query, Album.class,"quanzi_album_" + userId);

        List<Publish> publishList = new ArrayList<>();
        if (albumList != null) {
            for (Album album : albumList) {
                // 根据动态id查询发布动态表
                //审核通过的动态才会展示
                Query publishQuery = new Query(Criteria.where("_id").is(album.getPublishId()).and("state").is(1));
                Publish publish = mongoTemplate.findOne(publishQuery,Publish.class);
                if (publish != null) {
                    publishList.add(publish);
                }
            }
        }

        return new PageResult(page, pagesize, (int) count, publishList);
    }

    //更新朋友圈状态
    @Override
    public void update(String publishId, Integer state) {
        Query query = new Query(Criteria.where("_id").is(new ObjectId(publishId)));
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateFirst(query,update,Publish.class);
    }

    @Override
    public List<Publish> findByPid(List<Long> pidList) {
        Query query = new Query(Criteria.where("pid").in(pidList));
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        return publishList;
    }


    //动态审核翻页展示
    @Override
    public PageResult dynamicReview(Integer page, Integer pagesize, String state) {
        Query query = null;
        // 创建查询对象
        if (state==null|| state.equals("''") || state.isEmpty()) {
            query = new Query();
        } else {
            query = new Query(Criteria.where("state").is(Integer.parseInt(state)));
        }
        // 指定排序参数
        query.with(Sort.by(Sort.Direction.DESC, "created"));
        // 指定分页参
        query.limit(pagesize).skip((page - 1) * pagesize);
        // 查询当前用户的朋友圈动态
        List<Publish> publishList = mongoTemplate.find(query, Publish.class);
        // 获取总条数
        long count = mongoTemplate.count(query, Publish.class, "quanzi_publish");
        return new PageResult(page, pagesize, (int) count, publishList);
    }


    //审核通过
    @Override
    public void pass(String[] id) {
        for (String uid:id){
            ObjectId objectId = new ObjectId(uid);
            Query query = new Query(Criteria.where("_id").is(objectId).and("state").is(2));
            Update update = new Update();
            update.set("state", 1);
            mongoTemplate.updateFirst(query, update, Publish.class);
            Query query1 = new Query(Criteria.where("_id").is(objectId).and("state").is(0));
            Update update1 = new Update();
            update.set("state", 1);
            mongoTemplate.updateFirst(query1, update1, Publish.class);
        }
    }

    //审核拒绝
    @Override
    public void reject(String[] uid) {
        for (String id:uid){
            ObjectId objectId = new ObjectId(id);
            Query query = new Query(Criteria.where("_id").is(objectId).and("state").is(0));
            Update update = new Update();
            update.set("state", 2);
            mongoTemplate.updateFirst(query, update, Publish.class);
        }
    }
}
